<template>
  <div class="live-management-container">
    <div class="live-management-header">
      <h2 class="live-management-title">直播管理</h2>
      <div class="live-management-actions">
        <el-button
            type="primary"
            size="large"
            @click="showCreateDialog"
            v-if="!currentLive"
            class="create-live-btn"
            :icon="VideoPlay"
        >
          创建直播
        </el-button>

        <el-button
            type="danger"
            size="large"
            @click="endLive"
            v-else
            class="end-live-btn"
            :icon="VideoPause"
        >
          结束直播
        </el-button>
      </div>
    </div>

    <!-- 未创建直播时的描述信息 -->
    <div class="live-description" v-if="!currentLive">
      <el-card shadow="hover" class="description-card">
        <div class="description-content">
          <h3 class="description-title">欢迎使用直播功能</h3>
          <p class="description-text">
            通过我们的直播功能，您可以：
          </p>
          <ul class="description-list">
            <li><i class="el-icon-video-camera"></i> 实时展示您的产品和服务</li>
            <li><i class="el-icon-chat-line-round"></i> 与观众实时互动，解答疑问</li>
            <li><i class="el-icon-goods"></i> 展示和销售您的商品</li>
            <li><i class="el-icon-data-analysis"></i> 获取直播数据和分析报告</li>
            <li><i class="el-icon-mobile-phone"></i> 多平台同步直播，扩大影响力</li>
          </ul>
          <p class="description-text">
            创建直播后，您可以在直播过程中添加和管理商品，实时查看观看人数和互动数据。
          </p>
          <p class="description-text">
            立即创建您的第一场直播，开启全新的互动营销体验！
          </p>
        </div>
      </el-card>
    </div>

    <!-- 直播状态显示 -->
    <el-card class="live-status-card" v-if="currentLive" shadow="hover">
      <div class="live-status-content">
        <div class="live-status-header">
          <i class="el-icon-video-camera live-status-icon"></i>
          <h3 class="live-status-title">正在直播: {{ currentLive.liveTitle }}</h3>
        </div>
        <p class="live-status-description">{{ currentLive.description || '暂无描述信息' }}</p>

        <div class="live-status-info">
          <span class="live-status-item">
            <i class="el-icon-clock"></i>
            开始时间: {{ formatDate(currentLive.startTime) }}
          </span>
        </div>
      </div>
    </el-card>

    <!-- 直播商品管理 -->
    <div class="live-products-manager" v-if="currentLive">
      <el-card shadow="hover" class="products-manager-card">
        <div class="products-manager-header">
          <h3>直播商品管理</h3>
          <el-button
              type="primary"
              size="small"
              @click="showAddProductDialog"
              class="add-product-btn"
              :icon="Plus"
          >
            添加商品
          </el-button>
        </div>

        <!-- 商品列表 -->
        <div class="products-list">
          <el-table :data="liveProducts" style="width: 100%" v-loading="productsLoading">
            <el-table-column prop="name" label="商品名称" width="180"></el-table-column>
            <el-table-column prop="description" label="商品描述"></el-table-column>
            <el-table-column prop="price" label="价格" width="120">
              <template #default="scope">
                ¥{{ scope.row.price }}
              </template>
            </el-table-column>
            <el-table-column prop="origin" label="产地" width="100"></el-table-column>
            <el-table-column prop="stock" label="库存" width="100"></el-table-column>
            <el-table-column prop="unit" label="单位" width="100"></el-table-column>
            <el-table-column label="操作" width="120">
              <template #default="scope">
                <el-button
                    size="mini"
                    type="danger"
                    @click="del(scope.row.id)"
                >
                  下架
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
    </div>

    <!-- 创建直播的弹窗 -->
    <el-dialog
        v-model="createDialogVisible"
        title="创建新直播"
        width="500px"
        custom-class="create-live-dialog"
    >
      <el-form :model="liveForm" label-width="100px" class="live-form">
        <el-form-item label="直播标题" required>
          <el-input
              v-model="liveForm.liveTitle"
              placeholder="请输入直播标题"
              clearable
          />
        </el-form-item>

        <el-form-item label="直播描述">
          <el-input
              v-model="liveForm.description"
              type="textarea"
              placeholder="请输入直播描述"
              :rows="3"
              resize="none"
              clearable
          />
        </el-form-item>

        <el-form-item label="推流地址" required>
          <el-input
              v-model="rtmpUrl"
              placeholder="请输入推流地址"
              clearable
          />
          <div class="form-tip">
            <i class="el-icon-info"></i>
            请使用OBS等推流工具推流到此地址
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button size="medium" @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" size="medium" @click="startLive">开始直播</el-button>
      </template>
    </el-dialog>

    <!-- 添加商品的弹窗 -->
    <el-dialog
        v-model="addProductDialogVisible"
        title="添加直播商品"
        width="600px"
        custom-class="add-product-dialog"
    >
      <div class="add-product-content">
        <el-card shadow="hover" class="query-form-card">
          <div class="merchant-selector">
            <h4 class="merchant-selector-title">选择商家</h4>
            <el-radio-group v-model="queryDto.merchantId" class="merchant-radio-group">
              <el-radio
                  v-for="merchant in merchantList"
                  :key="merchant.id"
                  :label="merchant.id"
                  class="merchant-radio"
                  border
              >
                <div class="merchant-info">
                  <span class="merchant-name">{{ merchant.shopName }}</span>
                  <span class="merchant-id">ID: {{ merchant.id }}</span>
                </div>
              </el-radio>
            </el-radio-group>
          </div>
        </el-card>

        <el-form :model="productForm" label-width="100px" class="product-form">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="商品名称" required>
                <el-input v-model="productForm.name" placeholder="请输入商品名称" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商品产地" required>
                <el-input
                    v-model="productForm.origin"
                    placeholder="请输入商品产地"
                    clearable />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="价格" required>
                <el-input-number
                    v-model="productForm.price"
                    :min="0"
                    :precision="2"
                    :step="0.01"
                    controls-position="right"
                    style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="库存" required>
                <el-input-number
                    v-model="productForm.stock"
                    :min="0"
                    controls-position="right"
                    style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="单位" required>
            <el-input
                v-model="productForm.unit"
                placeholder="请输入单位"
                clearable
            />
          </el-form-item>

          <el-form-item label="商品描述">
            <el-input
                v-model="productForm.description"
                type="textarea"
                placeholder="请输入商品描述"
                :rows="3"
                resize="none"
                clearable
            />
          </el-form-item>

          <el-form-item label="商品图片" required>
            <el-upload
                class="avatar-uploader"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :http-request="customUpload"
            >
              <div class="avatar-wrapper">
                <img
                    v-if="productForm.imageUrls"
                    :src="productForm.imageUrls"
                    class="avatar-image"
                />
                <div v-else class="avatar-placeholder">
                  <el-icon class="upload-icon"><Plus /></el-icon>
                  <span class="upload-text">上传商品图片</span>
                </div>
                <div class="upload-mask">
                  <el-icon class="upload-icon"><Edit /></el-icon>
                  <span class="upload-text">更换图片</span>
                </div>
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  只能上传jpg/png文件，且不超过5MB
                </div>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <el-button size="medium" @click="addProductDialogVisible = false">取消</el-button>
        <el-button type="primary" size="medium" @click="addProduct">确认添加</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import axios from "axios";
import {VideoPlay, VideoPause, Plus, Edit} from '@element-plus/icons-vue'

const fileList = ref([])
const uploading = ref(false)

// 文件上传相关
const customUpload = async (options) => {
  const { file } = options
  try {
    uploading.value = true
    const formData = new FormData()
    formData.append('file', file)

    const response = await axios.post(BASE_URL+'/v1/file/upload', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })

    if (response.data.code == 2000) {
      ElMessage.success('图片上传成功')
      productForm.value.imageUrls = response.data.data
    } else {
      throw new Error(response.data.message || '上传失败')
    }
  } catch (error) {
    ElMessage.error('上传出错：' + error.message)
    throw error
  } finally {
    uploading.value = false
  }
}

const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }

  return isImage && isLt5M
}

// 定义查询表单数据
const queryDto = ref({
  merchantId: null,
  status: null
});
// 定义商家列表
const merchantList = ref([]);

// 获取商家列表
const getMerchantList = async () => {
  try {
    const response = await axios.get(`${BASE_URL}/api/v1/merchant/selStore`, {
      withCredentials: true
    });
    if (response.data.code == 2000) {
      merchantList.value = response.data.data;
      if (merchantList.value.length > 0) {
        queryDto.value.merchantId = merchantList.value[0].id; // 默认选择第一个商家
      }
    } else {
      ElMessage.error(response.data.msg || '获取商家列表失败');
    }
  } catch (error) {
    console.error('获取商家列表失败:', error);
    ElMessage.error('获取商家列表失败，请稍后重试');
  }
};
// 页面挂载时获取商家列表
onMounted(() => {
  getMerchantList();
});

const liveProducts = ref([]);

// 定义基础URL
const rtmpUrl = ref(null);
const productsLoading = ref(false);

// 处理推流地址转换为HLS地址
const convertToHlsUrl = (rtmpUrl) => {
  try {
    // 创建URL对象便于解析
    const urlObj = new URL(rtmpUrl);

    // 替换协议
    urlObj.protocol = 'http:';
    urlObj.port = '8080';

    // 处理路径名
    let pathname = urlObj.pathname;
    if (!pathname.endsWith('.m3u8')) {
      pathname = pathname.endsWith('/') ?
          `${pathname}playlist.m3u8` :
          `${pathname}.m3u8`;
      urlObj.pathname = pathname;
    }

    // 返回完整URL
    return urlObj.toString();
  } catch (e) {
    console.error('Invalid URL:', rtmpUrl);
    return rtmpUrl; // 返回原URL或处理错误
  }
};

// 创建直播弹窗是否显示
const createDialogVisible = ref(false)

// 添加商品弹窗是否显示
const addProductDialogVisible = ref(false)

// 当前直播信息
const currentLive = ref(null)

// 直播表单数据
const liveForm = ref({
  liveTitle: '',
  description: '',
  streamKey: ''
})

// 商品表单数据
const productForm = ref({
  name: '',
  liveId: null,
  merchantId: null,
  description: '',
  price: 0,
  stock: 0,
  unit: '斤',
  origin: '',
  imageUrls: ''
})

// 图片预览相关
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

// 显示创建直播弹窗
const showCreateDialog = () => {
  // 重置表单
  liveForm.value = {
    liveTitle: '',
    description: '',
    streamKey: ''
  }
  createDialogVisible.value = true
}

// 显示添加商品弹窗
const showAddProductDialog = () => {
  productForm.value = {
    id: null,
    name: '',
    liveId: null,
    merchantId: queryDto.value.merchantId, // 使用当前选中的商家ID
    description: '',
    price: 0,
    stock: 0,
    unit: '斤',
    origin: '',
    imageUrls: ''
  }
  addProductDialogVisible.value = true
}

// 定义保存直播id的对象
const liveId = ref(null);

// 开始直播
const startLive = () => {
  if (!liveForm.value.liveTitle) {
    ElMessage.error('请填写直播标题')
    return
  }

  if (!rtmpUrl.value) {
    ElMessage.error('请填写推流地址')
    return
  }

  liveForm.value.streamKey = convertToHlsUrl(rtmpUrl.value);

  axios.post(BASE_URL + '/api/v1/live/start', liveForm.value)
      .then((response) => {
        if (response.data.code == 2000) {
          ElMessage.success('直播已创建');
          liveId.value = response.data.data;
          console.log("开启直播返回的id:" + liveId.value);
          createDialogVisible.value = false;
          currentLive.value = {
            ...liveForm.value,
            startTime: new Date(),
            viewCount: 0,
            products: []
          }
          rtmpUrl.value = null;
        } else {
          ElMessage.error(response.data.msg);
        }
      })
}

// 结束直播
const endLive = () => {
  ElMessageBox.confirm('确定要结束当前直播吗？', '结束直播', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    customClass: 'end-live-confirm'
  }).then(() => {
    console.log("结束直播的id:" + liveId.value);
    axios.post(BASE_URL + '/api/v1/live/stop', null, {
      params: {
        id: liveId.value
      }
    }).then((response) => {
      if (response.data.code == 2000) {
        ElMessage.success('直播已结束');
        currentLive.value = null;
      } else {
        ElMessage.error(response.data.msg);
      }
    })
  }).catch(() => {
    ElMessage.info('已取消结束直播');
  });
}

// 添加商品
const addProduct = () => {
  if (!productForm.value.name) {
    ElMessage.error('请填写商品名称')
    return
  }

  if (!productForm.value.imageUrls) {
    ElMessage.error('请上传商品图片')
    return
  }

  if (productForm.value.price <= 0) {
    ElMessage.error('请填写正确的商品价格')
    return
  }

  if (productForm.value.stock < 0) {
    ElMessage.error('请填写正确的商品库存')
    return
  }

  productForm.value.liveId = liveId.value;
  productForm.value.merchantId = queryDto.value.merchantId;

  axios.post(BASE_URL + '/api/v1/product/addLiveProduct', productForm.value)
      .then((response) => {
        if (response.data.code == 2000) {
          ElMessage.success('商品添加成功');
          getProductList();
          addProductDialogVisible.value = false
          fileList.value = []
          productForm.value.imageUrls = ''
        } else {
          ElMessage.error(response.data.msg);
        }
      })
      .catch(error => {
        console.error('添加商品失败:', error)
        ElMessage.error('添加商品失败，请重试')
      })

  addProductDialogVisible.value = false
}

// 加载商品列表
const getProductList = () => {
  axios.get(BASE_URL + '/api/v1/product/liveProduct', {
    params: {
      liveId: liveId.value
    }
  }).then((response) => {
    if (response.data.code == 2000) {
      liveProducts.value = response.data.data;
    } else {
      ElMessage.error(response.data.msg);
    }
  })
}

// 下架商品
const del = (id) => {
  console.log("下架商品:" + id);
  axios.post(BASE_URL + '/api/v1/product/delLiveProduct', null, {params: {id: id}})
      .then((response) => {
        if (response.data.code == 2000) {
          getProductList();
        } else {
          ElMessage.error(response.data.msg);
        }
      })
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '未知时间';
  const d = new Date(date);
  return `${d.getFullYear()}-${padZero(d.getMonth() + 1)}-${padZero(d.getDate())} ${padZero(d.getHours())}:${padZero(d.getMinutes())}:${padZero(d.getSeconds())}`;
};

const padZero = (num) => {
  return num < 10 ? `0${num}` : num;
};
</script>

<style scoped>
.live-management-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.live-management-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.live-management-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.live-description {
  margin-top: 20px;
}

.description-card {
  border-radius: 8px;
  border: none;
}

.description-content {
  padding: 20px;
}

.description-title {
  margin: 0 0 16px 0;
  font-size: 20px;
  color: #303133;
  text-align: center;
}

.description-text {
  margin: 12px 0;
  color: #606266;
  line-height: 1.6;
  text-align: center;
}

.description-list {
  margin: 20px 0;
  padding: 0;
  list-style: none;
}

.description-list li {
  margin: 12px 0;
  padding: 8px 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  display: flex;
  align-items: center;
}

.description-list li i {
  margin-right: 10px;
  color: #409EFF;
}

.live-status-card {
  margin-top: 20px;
  border-radius: 8px;
  border: none;
}

.live-status-content {
  padding: 20px;
}

.live-status-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.live-status-icon {
  font-size: 24px;
  color: #409EFF;
  margin-right: 10px;
}

.live-status-title {
  margin: 0;
  font-size: 20px;
  color: #303133;
}

.live-status-description {
  margin: 16px 0;
  color: #606266;
  line-height: 1.6;
}

.live-status-info {
  display: flex;
  gap: 24px;
  margin-top: 20px;
  color: #606266;
}

.live-status-item i {
  margin-right: 8px;
  color: #909399;
}

.form-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
  display: flex;
  align-items: center;
}

.form-tip i {
  margin-right: 4px;
}

/* 商品管理样式 */
.live-products-manager {
  margin-top: 24px;
}

.products-manager-card {
  border-radius: 8px;
  border: none;
}

.products-manager-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.products-manager-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.add-product-btn {
  margin-left: auto;
}

.products-list {
  margin-top: 16px;
}

/* 添加商品弹窗样式 */
.add-product-content {
  padding: 10px;
}

.merchant-selector {
  margin-bottom: 20px;
}

.merchant-selector-title {
  margin: 0 0 15px 0;
  font-size: 16px;
  color: #303133;
}

.merchant-radio-group {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.merchant-radio {
  margin: 0;
  width: 100%;
}

.merchant-info {
  display: flex;
  flex-direction: column;
}

.merchant-name {
  font-weight: 500;
  margin-bottom: 4px;
}

.merchant-id {
  font-size: 12px;
  color: #909399;
}

/* 上传按钮样式 */
.avatar-uploader {
  --el-avatar-size: 148px;
}

.avatar-wrapper {
  position: relative;
  width: var(--el-avatar-size);
  height: var(--el-avatar-size);
  border-radius: 6px;
  overflow: hidden;
  border: 1px dashed var(--el-border-color);
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  color: #8c939d;
  background-color: #f5f7fa;
}

.upload-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  opacity: 0;
  transition: opacity 0.3s;
}

.avatar-wrapper:hover .upload-mask {
  opacity: 1;
}

.upload-icon {
  font-size: 28px;
  margin-bottom: 8px;
}

.upload-text {
  font-size: 14px;
}

/* 全局样式覆盖 */
:deep(.create-live-dialog .el-dialog__header) {
  border-bottom: 1px solid #ebeef5;
  margin-right: 0;
}

:deep(.create-live-dialog .el-dialog__body) {
  padding: 20px 24px;
}

:deep(.create-live-dialog .el-dialog__footer) {
  border-top: 1px solid #ebeef5;
  padding: 16px 24px;
  text-align: right;
}

:deep(.add-product-dialog .el-dialog__header) {
  border-bottom: 1px solid #ebeef5;
  margin-right: 0;
}

:deep(.add-product-dialog .el-dialog__body) {
  padding: 20px 24px;
}

:deep(.add-product-dialog .el-dialog__footer) {
  border-top: 1px solid #ebeef5;
  padding: 16px 24px;
  text-align: right;
}

:deep(.end-live-confirm .el-message-box__header) {
  padding-top: 20px;
}

:deep(.end-live-confirm .el-message-box__content) {
  padding: 10px 20px;
}

/* 表单布局优化 */
.product-form {
  margin-top: 20px;
}

:deep(.el-upload-list__item-thumbnail) {
  object-fit: cover;
}
</style>